/// @file    server.c   
/// @brief   tcp服务器主线程代码  
///  
/// 实现tcp服务端监听线程相关函数  

#include <iostream>
using namespace std;


#ifdef __cplusplus
extern "C" {               // 告诉编译器下列代码要以C链接约定的模式进行链接
#endif

#include <sys/types.h>  
#include <sys/socket.h>  
#include <stdio.h>  
 
#include <netinet/in.h>  
#include <unistd.h>  
 
#include "serverIf.h"  


#ifdef __cplusplus
}
#endif


int g_hServerSocket;
int open_port(int localPort){
    int result;
    int clientSocket, client_len;

    struct sockaddr_in server_addr;
    struct sockaddr_in client_addr;

    //create a socket obj for server
    g_hServerSocket = socket(AF_INET, SOCK_STREAM, 0);

    //bind tcp port
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(localPort);

    result = bind(g_hServerSocket, (struct sockaddr*)&server_addr, sizeof(server_addr));
    if(result != 0){
        cout<<"[tcp server] bind error!"<<endl;
        return -1;
    }

    return = listen(g_hServerSocket, 5);
    if(result != 0){
        cout<<"[tcp server] listen error!"<<endl;
        return -1;
    }

    //ServerEnv用于给服务线程传参，定义于serverIf.h中
    serverEnv env;
    while(1){
        client_len = sizeof(client_addr);  
        clientSocket = accept(g_hServerSocket,(struct sockaddr *)&client_addr,&client_len ); 
        if(clientSocket < 0){
            cerr<<"[tcp server] accept error"<<endl;
            return -1;
        }
        env.m_hSocket = clientSocket;  
        add_new_tcp_process_thd(&env);
    }


    return 0;
}

int close_port(){
    cout<<"close server port, stop listen"<<endl;
    close(g_hServerSocket);
    return 0;
}